﻿/**
 * Creation Date : December 15 2008
 * Author : Abdelkrim BOUTKHIL
 * 
 * Modification Date :
 * Modified by : 
 **/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using System.Configuration;
using Plugins;
using System.ComponentModel.Composition;

namespace Engine
{
    /// <summary>
    /// Entry point of the application. Reloads all the plugins and executes them 
    /// every [period] miliseconds.
    /// </summary>
    class Program
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        [Import]
        public IEnumerable<IPlugin> plugins { get; set; }
        public static void Main(string[] args)
        {
            logger.Info("CollaMail Engine Started");
            int period = int.Parse(ConfigurationManager.AppSettings["period"]);            
            // We use a timer to call the ProcessMails every [period] miliseconds 
            Program p = new Program();
            System.Threading.Timer timer = new System.Threading.Timer(p.Start, null, 0, period);
            // When user presses Enter, it ends the console application
            Console.Read();
            timer.Dispose();
            logger.Info("CollaMail Engine Ended");
        }

        /// <summary>
        /// Method which is started by System.Threading.Timer every [period] miliseconds
        /// Starts the plugins
        /// </summary>
        /// <param name="obj">null object just here for System.Threading.Timer</param>
        public void Start(object obj)
        {
            Compose();
            logger.Trace("Execution of plugins Started");
            logger.Trace("{0} plugins found in plugins directory", plugins.Count());
            foreach (IPlugin plugin in plugins)
            {
                plugin.Start();
                plugin.End();
            }
            logger.Trace("Execution of plugins Ended");
        }

        /// <summary>
        /// This method initialises all the plugins.
        /// It searches for plugins in the "Plugins" Assembly.
        /// It searches for plugins in the "Plugins" Directory.
        /// </summary>
        private void Compose()
        {
            var catalog = new DirectoryPartCatalog("Plugins", true);
            var container = new CompositionContainer(catalog);
            container.AddPart(this);
            container.Compose();
        }
    }
}
